package com.xiangty.reader;

import com.xiangty.bean.CustTemp;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 分区读取数据库
 */
@Configuration
public class MyBatisPagingItemReaderConfiguration {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     *
     * @param fromId    数据开始id
     * @param toId      数据结束id
     * @param range     分片数据
     * @return
     */
    @Bean("myBatisPagingItemReader")
    @StepScope
    public MyBatisPagingItemReader<CustTemp> myBatisPagingItemReader(
            @Value("#{stepExecutionContext[fromId]}") final String fromId,
            @Value("#{stepExecutionContext[toId]}") final String toId,
            @Value("#{stepExecutionContext[range]}") final String range
    ) {
        System.out.println("----------CommonPartitionMybatisItemReader开始-----fromId: " + fromId + "  -----toId:" + range + "  -----每片数量:" + range);
        MyBatisPagingItemReader<CustTemp> reader = new MyBatisPagingItemReader<CustTemp>();

        reader.setSqlSessionFactory(sqlSessionFactory);
        reader.setQueryId("com.xiangty.mapper.CustTempMapper.selectPartitionList3");
        Map<String, Object> parameterValues = new HashMap<>();
        parameterValues.put("fromId", fromId);
        parameterValues.put("toId", toId);
        reader.setParameterValues(parameterValues);

        int pageSize = range == null ? 1000 : Integer.parseInt(range) + 1000; // 默认的1000等于步骤的chunk参数值
        reader.setPageSize(pageSize); // 必须要大于每片的总条数，不然会默认为10条，write写方法的时候就会数据重复

        System.out.println("------------CommonPartitionMybatisItemReader结束-------------");
        return reader;
    }

}

